<template>
  <div class="wallet-freeze-container">
    <el-card class="freeze-card">
      <div slot="header" class="clearfix">
        <span>用户钱包冻结管理</span>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键词">
            <el-input 
              v-model="searchForm.keyword" 
              placeholder="请输入userid/openid/昵称/手机号"
              clearable
              @clear="handleReset"
            />
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select v-model="searchForm.state" placeholder="请选择">
              <el-option label="全部" value="" />
              <el-option label="正常" value="1" />
              <el-option label="冻结" value="0" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表区域 -->
      <div class="user-list-section">
        <h3>用户列表 (总数: {{ total }})</h3>
        
        <!-- 使用 v-for 直接渲染用户数据 -->
        <div v-if="!tableLoading && userList.length > 0" class="user-table-container">
          <!-- 表格头部 -->
          <div class="table-header">
            <div class="header-cell" style="width: 200px;">用户ID</div>
            <div class="header-cell" style="width: 260px;">用户账号</div>
            <div class="header-cell" style="width: 280px;">昵称</div>
            <div class="header-cell" style="width: 200px;">性别</div>
            <div class="header-cell" style="width: 280px;">手机号</div>
            <div class="header-cell" style="width: 220px;">会员等级</div>
            <div class="header-cell" style="width: 220px;">注册来源</div>
            <div class="header-cell" style="width: 200px;">状态</div>
            <div class="header-cell" style="width: 200px;">可用余额</div>
            <div class="header-cell" style="width: 200px;">冻结余额</div>
            <div class="header-cell" style="width: 200px;">支付密码锁定时间</div>
            <div class="header-cell" style="width: 200px;">操作</div>
          </div>
          
          <!-- 表格内容 -->
          <div class="table-body">
            <div 
              v-for="(user, index) in userList" 
              :key="user.buyerUserId || index"
              class="table-row"
              :class="{ 'row-even': index % 2 === 0, 'row-odd': index % 2 === 1 }"
            >
              <!-- 用户ID -->
              <div class="table-cell" style="width: 180px;">{{ user.buyerUserId || '--' }}</div>
              
              <!-- 用户账号 -->
              <div class="table-cell" style="width: 240px;">
                {{ user.account || user.phone || user.name || '未设置' }}
              </div>
              
              <!-- 昵称 -->
              <div class="table-cell" style="width: 260px;">{{ user.name || '--' }}</div>
              
              <!-- 性别 -->
              <div class="table-cell" style="width: 180px;">{{ getSexText(user.sex) }}</div>
              
              <!-- 手机号 -->
              <div class="table-cell" style="width: 260px;">{{ user.phone || '未设置' }}</div>
              
              <!-- 会员等级 -->
              <div class="table-cell" style="width: 200px;">{{ user.memberLevelName || '普通用户' }}</div>
              
              <!-- 注册来源 -->
              <div class="table-cell" style="width: 200px;">{{ getTerminalText(user.terminal) }}</div>
              
              <!-- 状态 -->
              <div class="table-cell" style="width: 200px;">
                <el-tag :type="user.state === 1 ? 'success' : 'danger'">
                  {{ user.state === 1 ? '正常' : '冻结' }}
                </el-tag>
              </div>
              
              <!-- 可用余额 -->
              <div class="table-cell" style="width: 200px;">
                {{ user.balance ? Number(user.balance).toFixed(2) : '0.00' }}
              </div>
              
              <!-- 冻结余额 -->
              <div class="table-cell" style="width: 200px;">
                {{ user.frozenBalance ? Number(user.frozenBalance).toFixed(2) : '0.00' }}
              </div>
              
              <!-- 支付密码锁定时间 -->
              <div class="table-cell" style="width: 200px;">
                {{ user.payPasswordLockTime || '未设置' }}
              </div>
              
              <!-- 操作 -->
              <div class="table-cell" style="width: 200px;">
                <div class="operation-buttons">
                  <!-- 冻结按钮 -->
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleFreezeClick(user)"
                    :disabled="!user || !user.buyerUserId"
                    v-if="user && user.buyerUserId && user.state === 1"
                  >
                    冻结
                  </el-button>

                  <!-- 解冻按钮 -->
                  <el-button
                    size="small"
                    type="warning"
                    @click="handleUnfreezeClick(user)"
                    :disabled="!user || !user.buyerUserId"
                    v-if="user && user.buyerUserId && user.state === 0"
                  >
                    解冻
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空数据状态 -->
        <div v-if="!tableLoading && userList.length === 0" class="empty-state">
          <el-empty 
            description="暂无用户数据" 
            :image-size="120"
          >
            <el-button type="primary" @click="loadUserList">重新加载</el-button>
          </el-empty>
        </div>

        <!-- 分页组件 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination-wrapper"
        ></el-pagination>
      </div>

      <!-- 冻结对话框 -->
      <el-dialog v-model="freezeDialogVisible" title="设置钱包冻结" width="500px" class="ban-dialog">
        <div v-if="freezeTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ freezeTargetUser.buyerUserId }}
            <span v-if="freezeTargetUser.userAccount || freezeTargetUser.phone || freezeTargetUser.name">
              （{{ freezeTargetUser.userAccount || freezeTargetUser.phone || freezeTargetUser.name }}）
            </span>
          </div>
          <el-form :model="freezeDialogForm" label-width="120px" :rules="freezeFormRules" ref="freezeForm">
            <el-form-item label="冻结金额" prop="amount">
              <el-input 
                v-model.number="freezeDialogForm.amount" 
                placeholder="请输入冻结金额"
                type="number"
                min="0"
              />
            </el-form-item>
            <el-form-item label="冻结时间" prop="expireTimeOption">
              <el-select 
                v-model="freezeDialogForm.expireTimeOption" 
                placeholder="请选择冻结时间"
                @change="handleExpireTimeChange"
              >
                <el-option label="1小时" value="1h"></el-option>
                <el-option label="1天" value="1d"></el-option>
                <el-option label="1周" value="1w"></el-option>
                <el-option label="1个月" value="1m"></el-option>
                <el-option label="1年" value="1y"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="冻结原因">
              <el-input 
                type="textarea" 
                :rows="3" 
                v-model="freezeDialogForm.reason" 
                placeholder="请输入冻结原因（可选）" 
              />
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="freezeDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="confirmFreeze">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 解冻对话框 -->
      <el-dialog v-model="unfreezeDialogVisible" title="确认解冻" width="500px" class="ban-dialog">
        <div v-if="unfreezeTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ unfreezeTargetUser.buyerUserId }}
            <span v-if="unfreezeTargetUser.userAccount || unfreezeTargetUser.phone || unfreezeTargetUser.name">
              （{{ unfreezeTargetUser.userAccount || unfreezeTargetUser.phone || unfreezeTargetUser.name }}）
            </span>
          </div>
          <p class="confirm-text">确定要解除该用户的钱包冻结状态吗？</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="unfreezeDialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="confirmUnfreeze">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'WalletFreezeManage',
  data() {
    return {
      submitLoading: false,
      tableLoading: false,

      // 搜索表单数据
      searchForm: {
        keyword: '',
        state: ''
      },

      // 冻结对话框
      freezeDialogVisible: false,
      freezeTargetUser: null,
      freezeDialogForm: {
        amount: 0,
        expireTimeOption: '', // 修改为选项值
        reason: ''
      },
      freezeFormRules: {
        amount: [
          { required: true, message: '请输入冻结金额', trigger: 'blur' },
          { type: 'number', message: '请输入数字', trigger: 'blur' }
        ],
        expireTimeOption: [
          { required: true, message: '请选择冻结时间', trigger: 'change' }
        ]
      },
      // 解冻对话框
      unfreezeDialogVisible: false,
      unfreezeTargetUser: null,

      // 用户列表相关
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableKey: 0
    }
  },

  methods: {
    // 获取性别文本
    getSexText(sex) {
      if (!sex) return '未设置'
      const sexMap = { '1': '男', '2': '女', '0': '未知' }
      return sexMap[sex] || sex
    },

    // 获取注册来源文本
    getTerminalText(terminal) {
      if (!terminal) return '未知'
      const terminalMap = {
        0: '未知',
        1: 'APP',
        2: '小程序',
        3: 'H5',
        4: '支付宝小程序',
        5: 'PC'
      }
      return terminalMap[terminal] || terminal
    },

    // 处理冻结点击
    handleFreezeClick(user) {
      if (!user) {
        this.$message.error('用户信息为空')
        return
      }

      if (typeof user.buyerUserId !== 'number' || user.buyerUserId <= 0) {
        this.$message.error('用户ID无效')
        return
      }

      this.openFreezeDialog(user)
    },

    openFreezeDialog(user) {
      this.freezeTargetUser = user
      this.freezeDialogForm.amount = 0
      this.freezeDialogForm.expireTimeOption = '' // 重置为选项值
      this.freezeDialogForm.reason = ''
      this.freezeDialogVisible = true
    },

    // 处理解冻点击
    handleUnfreezeClick(user) {
      if (!user || !user.buyerUserId) {
        this.$message.error('用户信息不完整，无法执行解冻');
        return;
      }
      this.openUnfreezeDialog(user);
    },

    openUnfreezeDialog(user) {
      this.unfreezeTargetUser = user
      this.unfreezeDialogVisible = true
    },

    // 处理冻结时间选项变化
    handleExpireTimeChange(value) {
      // 这里可以根据需要添加额外逻辑
      console.log('选择的冻结时间选项:', value);
    },

    // 计算冻结截止时间戳
    calculateExpireTime(option) {
      const now = new Date();
      switch (option) {
        case '1h': // 1小时
          return now.getTime() + 60 * 60 * 1000;
        case '1d': // 1天
          return now.getTime() + 24 * 60 * 60 * 1000;
        case '1w': // 1周
          return now.getTime() + 7 * 24 * 60 * 60 * 1000;
        case '1m': // 1个月（按30天计算）
          return now.getTime() + 30 * 24 * 60 * 60 * 1000;
        case '1y': // 1年（按365天计算）
          return now.getTime() + 365 * 24 * 60 * 60 * 1000;
        default:
          return null;
      }
    },

    // 提交冻结请求
    async confirmFreeze() {
      if (!this.freezeTargetUser) return;

      this.$refs.freezeForm.validate(async (valid) => {
        if (!valid) return;

        this.submitLoading = true;
        try {
          // 计算冻结截止时间戳
          const expireTime = this.calculateExpireTime(this.freezeDialogForm.expireTimeOption);
          
          const params = {
            buyerUserId: this.freezeTargetUser.buyerUserId,
            actionType: 2, // 2-冻结
            amount: this.freezeDialogForm.amount,
            expireTime: expireTime
          };

          const response = await request({
            url: '/buyerWallet/wallet/freezed',
            method: 'post',
            data: params
          });

          if (response.code === "200" || response.code === 200) {
            alert(response.message);
            this.freezeDialogVisible = false;
            this.loadUserList();
          } else if (response.code === "500") {
            alert(response.message);
            this.freezeDialogVisible = false;
          } else {
            let errorMessage = response.message;
                   alert(errorMessage);
                  this.freezeDialogVisible = false;
        
            
       
          }
        } catch (error) {
          let msg = '冻结失败：网络错误';
          if (error.response && error.response.data) {
            if (error.response.data.errorData && error.response.data.errorData.message) {
              msg = error.response.data.errorData.message;
            } else if (error.response.data.message) {
              msg = error.response.data.message;
            } else if (error.response.data.error) {
              msg = error.response.data.error;
            }
          } else if (error.message) {
            msg = error.message;
          }
          this.$message.error(msg);
          this.freezeDialogVisible = false;
        } finally {
          this.submitLoading = false;
        }
      });
    },

    // 提交解冻请求
    async confirmUnfreeze() {
      if (!this.unfreezeTargetUser) return;

      this.submitLoading = true;
      try {
        const params = {
          buyerUserId: this.unfreezeTargetUser.buyerUserId,
          actionType: 1, // 1-解冻
          amount: 0,
          expireTime: ''
        };

        const response = await request({
          url: '/buyerWallet/wallet/freezed',
          method: 'post',
          data: params,
        });

        // 检查响应状态码
        if (response.code === "200" || response.code === 200) {
          this.$message.success('解冻成功');
          alert(response.message);  
          this.unfreezeDialogVisible = false;
          this.loadUserList();
        } else if (response.code === "500") {
             alert(response.message);  
          this.unfreezeDialogVisible = false;
        } else {
          // 其他错误码
          let errorMessage = response.message || '解冻失败';
          
          // 如果有 errorData 且包含 message，则使用 errorData.message
          if (response.errorData && response.errorData.message) {
            errorMessage = response.errorData.message;
             this.alert(errorMessage)
            this.unfreezeDialogVisible = false;
          }
          
         
        }
      } catch (error) {
        let msg = '解冻失败：网络错误';
        if (error.response && error.response.data) {
          if (error.response.data.errorData && error.response.data.errorData.message) {
            msg = error.response.data.errorData.message;
          } else if (error.response.data.message) {
            msg = error.response.data.message;
          } else if (error.response.data.error) {
            msg = error.response.data.error;
          }
        } else if (error.message) {
          msg = error.message;
        }
        this.$message.error(msg);
        this.unfreezeDialogVisible = false;
      } finally {
        this.submitLoading = false;
      }
    },

    // 查询用户列表
    async loadUserList() {
      this.tableLoading = true
      try {
        const response = await request({
          url: '/userManage/getUserList',
          method: 'get',
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            search: this.searchForm.keyword,
            state: this.searchForm.state
          }
        })

        if (response.code === "200" || response.code === 200) {
          const data = response.data

          let userList = []
          let total = 0

          if (data && data.list && Array.isArray(data.list)) {
            userList = data.list.filter(item => item && item.buyerUserId)
            total = data.total || 0
          } else if (data && Array.isArray(data)) {
            userList = data.filter(item => item && item.buyerUserId)
            total = userList.length
          } else {
            this.$message.error('数据格式错误')
            return
          }

          const validatedList = userList.map(item => ({
            buyerUserId: item.buyerUserId || 0,
            name: item.name || '',
            sex: item.sex || '',
            phone: item.phone || '',
            memberLevelName: item.memberLevelName || '普通用户',
            terminal: item.terminal || 0,
            state: item.state || 0,
            ifBlack: item.ifBlack || 0,
            userAccount: item.userAccount || '',
            balance: item.balance || 0,
            frozenBalance: item.frozenBalance || 0,
            payPasswordLockTime: item.payPasswordLockTime || '',
            account: item.account || '',
            ...item
          }))

          this.userList = validatedList
          this.total = total
        } else {
          this.$message.error(response.message || '加载失败')
        }
      } catch (error) {
        this.$message.error('加载用户列表失败：' + (error.message || '网络错误'))
      } finally {
        this.tableLoading = false
      }
    },

    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.loadUserList()
    },

    // 处理重置
    handleReset() {
      this.searchForm.keyword = ''
      this.searchForm.state = ''
      this.currentPage = 1
      this.loadUserList()
    },

    // 分页事件处理
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadUserList()
    }
  },

  mounted() {
    this.loadUserList()
  }
}
</script>

<style scoped>
/* 主容器样式 */
.wallet-freeze-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 卡片样式 */
.freeze-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.freeze-card .el-card__header {
  background-color: #409eff;
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.freeze-card .el-card__header span {
  font-size: 16px;
  font-weight: 600;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 用户列表区域样式 */
.user-list-section {
  margin-top: 20px;
}

.user-list-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

/* 表格样式 */
.user-table-container {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  background: white;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 2px solid #e4e7ed;
}

.header-cell {
  padding: 12px 8px;
  font-weight: 600;
  color: #606266;
  text-align: center;
  border-right: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-cell:last-child {
  border-right: none;
}

.table-body {
  max-height: 600px;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s ease;
}

.table-row:hover {
  background-color: #f5f7fa;
}

.row-even {
  background-color: #fafafa;
}

.row-odd {
  background-color: white;
}

.table-cell {
  padding: 12px 8px;
  text-align: center;
  border-right: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.table-cell:last-child {
  border-right: none;
}

/* 操作按钮样式 */
.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.operation-buttons .el-button {
  margin: 0;
  border-radius: 4px;
  font-weight: 500;
}

.operation-buttons .el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.operation-buttons .el-button--warning {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.operation-buttons .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

/* 状态标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 4px 8px;
}

.el-tag--success {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

.el-tag--danger {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c;
}

.el-tag--info {
  background-color: #f4f4f5;
  border-color: #909399;
  color: #909399;
}

/* 分页组件样式 */
.pagination-wrapper {
  text-align: center;
  margin-top: 20px;
  padding: 20px 0;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.el-pagination .el-pagination__total {
  margin-right: 15px;
  color: #606266;
}

.el-pagination .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-wrapper .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pager li.active {
  background-color: #409eff !important;
  color: white !important;
  font-weight: 600;
  transform: scale(1.05);
}

.el-pagination .el-pager li.active {
  background-color: #409eff;
  color: white;
}

/* 对话框样式 */
.ban-dialog .el-dialog__header,
.unban-dialog .el-dialog__header {
  background-color: #409eff;
  color: white;
  border-radius: 8px 8px 0 0;
}

.ban-dialog .el-dialog__title,
.unban-dialog .el-dialog__title {
  color: white;
  font-weight: 600;
}

.ban-dialog .el-dialog__body,
.unban-dialog .el-dialog__body {
  padding: 20px;
}

.user-info {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
  color: #606266;
  line-height: 1.6;
}

.confirm-text {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 600;
  color: #303133;
}

.el-input,
.el-select,
.el-input-number {
  border-radius: 4px;
}

.el-input:focus,
.el-select:focus,
.el-input-number:focus {
  border-color: #409eff;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.dialog-footer .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
}

.dialog-footer .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-footer .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .wallet-freeze-container {
    padding: 15px;
  }
  
  .el-table th,
  .el-table td {
    padding: 8px 4px;
    font-size: 13px;
  }
  
  .operation-buttons .el-button {
    padding: 6px 12px;
    font-size: 12px;
  }
}

@media (max-width: 768px) {
  .wallet-freeze-container {
    padding: 10px;
  }
  
  .freeze-card .el-card__header {
    padding: 12px 15px;
  }
  
  .user-list-section h3 {
    font-size: 16px;
  }
  
  .debug-info {
    padding: 12px;
    font-size: 12px;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .el-dialog {
    width: 90% !important;
    margin: 5vh auto;
  }
  
  .operation-buttons {
    flex-direction: column;
    gap: 5px;
  }
  
  .operation-buttons .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .wallet-freeze-container {
    padding: 5px;
  }
  
  .freeze-card {
    margin-bottom: 10px;
  }
  
  .user-list-section {
    margin-top: 10px;
  }
  
  .debug-info {
    padding: 10px;
    margin-bottom: 15px;
  }
  
  .pagination-wrapper {
    padding: 15px 0;
  }
}
</style>